package com.laiketui.admin.store.service.dubbo.users;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.laiketui.admin.store.api.users.UserManagerService;
import com.laiketui.admin.store.consts.StoreConst;
import com.laiketui.common.api.PublicAddressService;
import com.laiketui.common.api.PublicMemberService;
import com.laiketui.common.api.PublicUserService;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.distribution.PubliceDistributionService;
import com.laiketui.common.api.ocr.OcrService;
import com.laiketui.common.api.ocr.VerifyService;
import com.laiketui.common.mapper.*;
import com.laiketui.common.utils.tool.PriceUtils;
import com.laiketui.common.utils.tool.cache.RedisDataTool;
import com.laiketui.common.utils.tool.data.DataCheckTool;
import com.laiketui.common.utils.tool.file.EasyPoiExcelUtil;
import com.laiketui.common.utils.tool.str.StringUtils;
import com.laiketui.core.cache.RedisUtil;
import com.laiketui.core.common.SplitUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DataUtils;
import com.laiketui.core.utils.tool.DateUtil;
import com.laiketui.domain.config.ConfigModel;
import com.laiketui.domain.distribution.DistributionConfigModel;
import com.laiketui.domain.distribution.UserDistributionModel;
import com.laiketui.domain.file.FileDeliveryModel;
import com.laiketui.domain.lktconst.DictionaryConst;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.log.AdminRecordModel;
import com.laiketui.domain.mch.AdminModel;
import com.laiketui.domain.mch.MchModel;
import com.laiketui.domain.mch.RoleModel;
import com.laiketui.domain.mch.UserCollectionModel;
import com.laiketui.domain.ocr.VerifyBusinessData;
import com.laiketui.domain.order.OrderDetailsModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.user.User;
import com.laiketui.domain.user.UserAddress;
import com.laiketui.domain.user.UserBusinessInfo;
import com.laiketui.domain.user.UserRuleModel;
import com.laiketui.domain.vo.MainVo;
import com.laiketui.domain.vo.Tool.ExcelAnalysisVo;
import com.laiketui.domain.vo.user.AddUserVo;
import com.laiketui.domain.vo.user.ExamineUserVo;
import com.laiketui.domain.vo.user.UpdateUserVo;
import com.laiketui.domain.vo.user.UserVo;
import com.laiketui.root.common.BuilderIDTool;
import kotlin.jvm.Throws;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;

/**
 * 会员管理
 *
 * @author Trick
 * @date 2021/1/7 10:58
 */
@Service
public class UserManagerServiceImpl implements UserManagerService {
    private final Logger logger = LoggerFactory.getLogger(UserManagerServiceImpl.class);

    @Autowired
    private ConfigModelMapper configModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Autowired
    private PublicMemberService publicMemberService;

    @Autowired
    private PublicAddressService publicAddressService;

    @Autowired
    private CustomerModelMapper customerModelMapper;

    @Autowired
    private FileDeliveryModelMapper fileDeliveryModelMapper;

    @Autowired
    private UserBusinessInfoMapper userBusinessInfoMapper;
    @Autowired
    private RoleModelMapper roleModelMapper;
    @Autowired
    private VerifyService verifyService;

    @Override
    public Map<String, Object> getUserInfo(UserVo vo, HttpServletResponse response) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            User queryUser = new User();
            queryUser.setStore_id(vo.getStoreId());
            queryUser.setUser_id(vo.getUid());
            queryUser.setGrade(vo.getGrade());
            queryUser.setIs_out(StringUtils.toString(vo.getIsOverdue()));
            queryUser.setSource(StringUtils.toString(vo.getSource()));
            Map<String, Object> parmaMap = JSON.parseObject(JSON.toJSONString(queryUser), new TypeReference<Map<String, Object>>() {
            });
            if (StringUtils.isNotEmpty(vo.getKey())) {
                parmaMap.put("key", vo.getKey());
            }
            //获取当前自营店
            String storeUserId = customerModelMapper.getStoreUserId(vo.getStoreId());

            parmaMap.put("userName", vo.getUname());
            parmaMap.put("tel", vo.getTel());
            parmaMap.put("Register_data_sort", DataUtils.Sort.DESC.toString());
            parmaMap.put("isStore", "isStore");
            parmaMap.put("pageStart", vo.getPageNo());
            parmaMap.put("pageEnd", vo.getPageSize());
//            parmaMap.put("userType",2);
            List<Map<String, Object>> userList = userBaseMapper.selectDynamic(parmaMap);
            int total = userBaseMapper.countDynamic(parmaMap);
            for (Map<String, Object> map : userList) {
                map.put("user_name", map.get("user_name"));
                //用户id
                String userId = String.valueOf(map.get("user_id"));
                //用户的等级id
                int levelId = StringUtils.stringParseInt(String.valueOf(map.get("grade")));
                //订单类型
                String orderType = DictionaryConst.OrdersType.ORDERS_HEADER_GM;

                //获取用户消费金额
                Long userOrderPrice = orderModelMapper.sumUserOrderPrice(vo.getStoreId(), userId);
                BigDecimal orderPrice = PriceUtils.longToBigDecimalPrice(userOrderPrice);

                //用户以退款金额
//                BigDecimal refundPrice = orderModelMapper.sumUserOrderRefundPrice(vo.getStoreId(), userId);
                //用户实际消费金额
                map.put("z_price", orderPrice);
                //获取用户有效订单数量
                int orderNum = orderModelMapper.countUserEffectiveOrdernoNum(vo.getStoreId(), userId);
                map.put("z_num", orderNum);

                String registerDate = DateUtil.dateFormate(MapUtils.getString(map, "Register_data"), GloabConst.TimePattern.YMDHMS);
                String gradeEndDate = "暂无";
                if (map.containsKey("grade_end")) {
                    gradeEndDate = DateUtil.dateFormate(MapUtils.getString(map, "grade_end"), GloabConst.TimePattern.YMDHMS);
                }
                map.put("Register_data", registerDate);
                map.put("grade_end", gradeEndDate);

                //身份名称
                String roleId = MapUtils.getString(map, "role_id");
                if(StringUtils.isNotEmpty(roleId)){
                    RoleModel roleModel = new RoleModel();
                    roleModel.setId(Integer.valueOf(roleId));
                    roleModel = roleModelMapper.selectOne(roleModel);
                    map.put("roleName",roleModel.getName());
                }

                //获取用户等级
//                String levelName = "普通会员";
//                String gradeDiscount = "暂无折扣";
//                UserGradeModel userGradeModel = new UserGradeModel();
//                userGradeModel.setStore_id(vo.getStoreId());
//                userGradeModel.setId(levelId);
//                userGradeModel = userGradeModelMapper.selectOne(userGradeModel);
//                if (userGradeModel != null) {
//                    levelName = userGradeModel.getName();
//                    //获取会员折扣
//                    BigDecimal vipDic = BigDecimal.valueOf(publicMemberService.getMemberGradeRate(orderType, userId, vo.getStoreId()));
//                    if (new BigDecimal("1").compareTo(vipDic) != 0) {
//                        gradeDiscount = vipDic.toString();
//                    }
//                }
//                map.put("grade", levelName);
//                map.put("gradeDiscount", gradeDiscount);

                String birthday = "";
                if (map.containsKey("birthday")) {
                    birthday = DateUtil.dateFormate(MapUtils.getString(map, "birthday"), GloabConst.TimePattern.YMDHMS);
                }
                map.put("birthday", birthday);
                String clientId = MapUtils.getString(map, "clientid");
                map.put("clientId", clientId);

                //是否有密码
                User user = userBaseMapper.selectByPrimaryKey(MapUtils.getString(map, "id"));
                boolean loginPwd = StringUtils.isNotEmpty(user.getMima());
                map.put("loginPwd", loginPwd);
                boolean isPaymentPwd = StringUtils.isNotEmpty(user.getPassword());
                map.put("isPaymentPwd", isPaymentPwd);

                //判断店铺是否是该用户的
                int isMch = 0;
                int count = mchModelMapper.countMchIsByUser(vo.getStoreId(), userId);
                if (count > 0) {
                    isMch = 1;
                }
                map.put("is_mch", isMch);
                //是否有删除按钮
                map.put("isDelBtn", !userId.equals(storeUserId));

                map.put("last_time", MapUtils.getString(map, "last_time"));
                //获取当前用户默认地址
                UserAddress userAddress = publicAddressService.findAddress(vo.getStoreId(), userId, null);
                map.put("userAddress", userAddress);
            }
            if (vo.getExportType() == 1) {
                exportUserList(userList, response);
                return null;
            }


            resultMap.put("total", total);
            resultMap.put("list", userList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("加载会员列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getUserInfo");
        }
        return resultMap;
    }

    private void exportUserList(List<Map<String, Object>> goodsList, HttpServletResponse response) throws LaiKeAPIException {
        try {
            //表头
            String[] headerList = new String[]{"用户ID", "用户头像", "用户名称", "用户账号", "手机号码", "账户余额", "积分余额", "账号来源", "有效订单数", "交易金额", "注册时间"};
            //对应字段
            String[] kayList = new String[]{"user_id", "headimgurl", "user_name", "zhanghao", "mobile", "money", "score", "sourceName", "z_num", "z_price", "Register_data"};
            EasyPoiExcelUtil.excelExport("用户列表", headerList, kayList, goodsList, response);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("导出用户数据 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "exportGoodsData");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUserById(UpdateUserVo vo) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            int count;
            if (StringUtils.isEmpty(vo.getUserId())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_BNWK, "userid不能为空", "updateUserById");
            }
            User user = new User();
            user.setStore_id(vo.getStoreId());
            user.setUser_id(vo.getUserId());
            user = userBaseMapper.selectOne(user);
            if (user == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHBCZ, "用户不存在", "updateUserById");
            }
            User updateUser = new User();
            updateUser.setId(user.getId());
            updateUser.setUser_id(user.getUser_id());
//            updateUser.setUser_name(vo.getUname());
//            updateUser.setMobile(vo.getPhone());
            updateUser.setMima(vo.getPwd());
            updateUser.setPassword(vo.getPaypwd());
            updateUser.setScore(vo.getJifen());
            updateUser.setSex(vo.getSex());
            updateUser.setRole_id(vo.getRoleId());
            updateUser.setSignatory_type(vo.getSignatoryType());
            updateUser.setIndustry(vo.getIndustry());
//            updateUser.setCompanyCreditCode(vo.getCompanyCreditCode());
            if(StringUtils.isNotEmpty(vo.getProvince())){
                updateUser.setProvince(vo.getProvince());
            }
            if(StringUtils.isNotEmpty(vo.getCity())){
                updateUser.setCity(vo.getCity());
            }
            if(StringUtils.isNotEmpty(vo.getArea())){
                updateUser.setCounty(vo.getArea());
            }
            updateUser.setDetailed_address(vo.getDetailedAddress());
            if(updateUser.getSignatory_type() == 1){
                updateUser.setUser_name(vo.getSignatoryName());
                updateUser.setSignatory_name(vo.getSignatoryName());
                updateUser.setId_card(vo.getIdCard());
            }
            if(updateUser.getSignatory_type() != 1){
                updateUser.setCompany_name(vo.getSignatoryName());
                updateUser.setCompany_credit_code(vo.getCompanyCreditCode());
                updateUser.setUser_name(vo.getLegalPerson());
                updateUser.setSignatory_name(vo.getSignatoryName());
                updateUser.setId_card(vo.getLegalPersonIdCard());
            }
            //修改资质信息
            updateUser.setId_card_face_img(vo.getIdCardFaceImg());
            updateUser.setId_card_back_img(vo.getIdCardBackImg());
            updateUser.setBusiness_license_img(vo.getBusinessLicenseImg());
            updateUser.setDeliveryType(vo.getDeliveryType());
            updateUser.setInvoice(vo.getInvoice());
            updateUser.setSettlementType(vo.getSettlementType());
            if(StringUtils.isNotEmpty(vo.getSignTime())){
                updateUser.setSign_time(DateUtil.dateFormateToDate(vo.getSignTime(), GloabConst.TimePattern.YMD));
            }
            updateUser.setRemark(vo.getRemark());
//            if (vo.getMoney().compareTo(new BigDecimal("9999999999.99")) > 0) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YEYCGSX, "余额已超过上限");
//            }
//            updateUser.setMoney(vo.getMoney());
//            updateUser.setBirthday(DateUtil.dateFormateToDate(vo.getBirthday(), GloabConst.TimePattern.YMDHMS));
//            if(vo.getHeaderUrl() != null){
//                updateUser.setHeadimgurl(vo.getHeaderUrl());
//            }
            //验证数据
            updateUser = DataCheckTool.checkUserDataFormate(updateUser);
            if (updateUser.equals(new User())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XGSBCSCW, "修改失败,参数错误", "updateUserById");
            }
//            if (StringUtils.isNotEmpty(vo.getUname()) && !user.getUser_name().equals(vo.getUname())) {
//                if (!DataCheckTool.checkLength(user.getUser_name(), 0, 16)) {
//                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHMGSBZQ, "用户名格式不正确");
//                }
//            }
//            if (StringUtils.isNotEmpty(vo.getPhone()) && !vo.getPhone().equals(user.getMobile())) {
//                int flag = userBaseMapper.validataPhoneOrNoIsRegister(vo.getStoreId(), vo.getPhone(),user.getId());
//                if (flag > 0) {
//                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJHMYCZ, "手机号码已存在");
//                }
//            }

            count = userBaseMapper.updateByPrimaryKeySelective(updateUser);
            if (count < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_XGSB, "修改失败", "updateUserById");
            }
            //修改工商信息
            UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
            userBusinessInfo.setUserId(updateUser.getUser_id());
            UserBusinessInfo updateBusinessInfo = userBusinessInfoMapper.selectOne(userBusinessInfo);
            if(updateBusinessInfo != null){
                updateBusinessInfo.setBusinessLicenseImg(updateUser.getBusiness_license_img());
                updateBusinessInfo.setIdCardBackImg(updateUser.getId_card_back_img());
                updateBusinessInfo.setIdCardFaceImg(updateUser.getId_card_face_img());
                updateBusinessInfo.setSignatoryName(updateUser.getSignatory_name());
                updateBusinessInfo.setRealName(updateUser.getUser_name());
                updateBusinessInfo.setSignatoryCreditCode(updateUser.getCompany_credit_code());
                updateBusinessInfo.setSignatoryLegalPersonIdCard(updateUser.getId_card());
                updateBusinessInfo.setIdCard(updateUser.getId_card());
                updateBusinessInfo.setSignatoryType(updateUser.getSignatory_type());
                userBusinessInfoMapper.updateByPrimaryKeySelective(updateBusinessInfo);
            }
            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(), "修改了用户ID："+vo.getUserId()+" 的信息",AdminRecordModel.Type.UPDATE, vo.getAccessId());
            return true;
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("修改用户资料 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "updateUserById");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examineUserInformation(ExamineUserVo vo) {
        AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        String message = "";
        String userId = vo.getUserId();
        Integer examineFlag = vo.getExamineFlag();
        User user = userBaseMapper.selectByUserId(vo.getStoreId(), userId);
        if(Objects.isNull(user)){
            throw new LaiKeAPIException("查无此用户");
        }
        if(StringUtils.isEmpty(userId) || Objects.isNull(examineFlag)){
            throw new LaiKeAPIException("参数错误");
        }
        if(examineFlag == 1){
            user.setExamine_flag(GloabConst.UserExamineFlag.USER_EXAMINE_PASS);
            user.setUser_type(GloabConst.UserType.USER_TYPE_BUSINESS);
            user.setRole_id(GloabConst.RoleType.ROLE_MEMBER);
            user.setSign_time(new Date());
            UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
            userBusinessInfo.setUserId(user.getUser_id());
            userBusinessInfo.setSignatoryName(user.getSignatory_name());
            userBusinessInfo.setSignatoryType(user.getSignatory_type());
            userBusinessInfo.setSignatoryLegalPerson(user.getUser_name());
            userBusinessInfo.setSignatoryLegalPersonIdCard(user.getId_card());
            userBusinessInfo.setSignatoryCreditCode(user.getCompany_credit_code());
            userBusinessInfo.setRealName(user.getUser_name());
            userBusinessInfo.setIdCard(user.getId_card());
            userBusinessInfo.setProvince(user.getProvince());
            userBusinessInfo.setCity(user.getCity());
            userBusinessInfo.setArea(user.getCounty());
            userBusinessInfo.setAddress(user.getDetailed_address());
            userBusinessInfoMapper.insertSelective(userBusinessInfo);
            userBaseMapper.updateByPrimaryKeySelective(user);
            return "审核通过";
        }
        if(examineFlag == 0){
            user.setExamine_flag(GloabConst.UserExamineFlag.USER_EXAMINE_NO_PASS);
            user.setSubmit_flag(GloabConst.UserSubmitFLag.USER_SUBMIT_FLAG_NOT_SUBMIT);
            user.setSignatory_type(null);
            user.setSignatory_name(null);
            user.setCompany_credit_code(null);
            user.setUser_name(null);
            user.setId_card(null);
            user.setProvince(null);
            user.setCity(null);
            user.setCounty(null);
            user.setDetailed_address(null);
            userBaseMapper.updateByPrimaryKeySelective(user);
            return "审核不通过";
        }
        return message;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String examineBusinessInformation(ExamineUserVo vo) {
        AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
        String message = "";
        String userId = vo.getUserId();
        Integer examineFlag = vo.getExamineFlag();
        User user = userBaseMapper.selectByUserId(vo.getStoreId(), userId);
        if(Objects.isNull(user)){
            throw new LaiKeAPIException("查无此用户");
        }
        if(StringUtils.isEmpty(userId) || Objects.isNull(examineFlag)){
            throw new LaiKeAPIException("参数错误");
        }
        if(examineFlag == 1){
            user.setExamine_flag(GloabConst.UserExamineFlag.USER_EXAMINE_PASS);
            user.setUser_type(GloabConst.UserType.USER_TYPE_BUSINESS);
            user.setSign_time(new Date());
            UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
            userBusinessInfo.setUserId(user.getUser_id());
            userBusinessInfo.setSignatoryName(user.getSignatory_name());
            userBusinessInfo.setSignatoryType(user.getSignatory_type());
            userBusinessInfo.setSignatoryLegalPerson(user.getUser_name());
            userBusinessInfo.setSignatoryLegalPersonIdCard(user.getId_card());
            userBusinessInfo.setSignatoryCreditCode(user.getCompany_credit_code());
            userBusinessInfo.setIdCardFaceImg(user.getId_card_face_img());
            userBusinessInfo.setIdCardBackImg(user.getId_card_back_img());
            userBusinessInfo.setBusinessLicenseImg(user.getBusiness_license_img());
            userBusinessInfo.setRealName(user.getUser_name());
            userBusinessInfo.setIdCard(user.getId_card());
            userBusinessInfo.setProvince(user.getProvince());
            userBusinessInfo.setCity(user.getCity());
            userBusinessInfo.setArea(user.getCounty());
            userBusinessInfo.setAddress(user.getDetailed_address());
            userBusinessInfoMapper.insertSelective(userBusinessInfo);
            userBaseMapper.updateByPrimaryKeySelective(user);
            publiceService.sendSms(1, user.getMobile(), GloabConst.VcodeCategory.TYPE_NOTICE, GloabConst.VcodeCategory.BUSINESS_CODE, null);
            return "审核通过";
        }
        if(examineFlag == -1){
            user.setExamine_flag(GloabConst.UserExamineFlag.USER_EXAMINE_NO_PASS);
            user.setSubmit_flag(GloabConst.UserSubmitFLag.USER_SUBMIT_FLAG_NOT_SUBMIT);
            user.setSignatory_type(null);
            user.setSignatory_name(null);
            user.setCompany_credit_code(null);
            user.setUser_name(null);
            user.setId_card(null);
            user.setProvince(null);
            user.setCity(null);
            user.setCounty(null);
            user.setDetailed_address(null);
            user.setBusiness_license_img(null);
            user.setId_card_back_img(null);
            user.setId_card_face_img(null);
            userBaseMapper.updateByPrimaryKeySelective(user);
            return "审核不通过";
        }
        return message;
    }

    @Override
    public Map<String, Object> getUserGradeType(MainVo vo) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            UserRuleModel userRuleModel = userRuleModelMapper.getUserRule(vo.getStoreId());
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (userRuleModel != null) {
                String gradeType = userRuleModel.getMethod();
                String[] list = gradeType.split(SplitUtils.DH);
                for (String type : list) {
                    Map<String, Object> map = new HashMap<>(16);
                    map.put("value", type);
                    switch (type) {
                        case "1":
                            map.put("label", "包月");
                            break;
                        case "2":
                            map.put("label", "包季");
                            break;
                        case "3":
                            map.put("label", "包年");
                            break;
                        default:
                            break;
                    }
                    resultList.add(map);
                }
            }

            resultMap.put("gradeType", resultList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("获取会员配置升级方式 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getUserGradeType");
        }
        return resultMap;
    }

    @Override
    public boolean userRechargeMoney(MainVo vo, int id, BigDecimal money, Integer type, String remake) throws LaiKeAPIException {
        try {
            AdminModel userCache = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            if (type == null) {
                type = 1;
            }
            //获取用户信息
            User user = userBaseMapper.selectByPrimaryKey(id);
            String event = "";
            //添加操作日志
            if (type==1){
                event = "将用户ID："+user.getUser_id()+"充值了："+money+"余额";
            }else{
                event = "将用户ID："+user.getUser_id()+"充值了："+money+"积分";
            }

            publiceService.addAdminRecord(vo.getStoreId(), event,AdminRecordModel.Type.UPDATE, vo.getAccessId());
            return publicUserService.userRechargeMoney(vo.getStoreId(), id, money, type, null, remake);


        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("会员充值余额 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "userRechargeMoney");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delUserById(MainVo vo, int id) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            //获取用户信息
            User user = userBaseMapper.selectByPrimaryKey(id);
            if (user == null) {
                logger.error("用户删除失败:用户不存在");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHBCZ, "用户不存在", "delUserById");
            }
            if (user.getMoney() != null && user.getMoney().doubleValue() > 0) {
                logger.error("用户删除失败:该用户有余额未使用");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSBGYHYYEWSY, "删除失败:该用户有余额未使用", "delUserById");
            }
            int count = orderModelMapper.countUserUnfinishedOrder(vo.getStoreId(), user.getUser_id());
            if (count > 0) {
                logger.error("用户删除失败:该用户有未完成的订单");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSBGYHYWWCDDD, "删除失败:该用户有未完成的订单", "delUserById");
            }
            //判断店铺是否未注销
            MchModel mchModel = new MchModel();
            mchModel.setUser_id(user.getUser_id());
            mchModel.setStore_id(vo.getStoreId());
            mchModel.setRecovery(DictionaryConst.ProductRecycle.NOT_STATUS);
            mchModel = mchModelMapper.selectOne(mchModel);
            if (mchModel != null && DictionaryConst.MchExameStatus.EXAME_PASS_STATUS.toString().equals(mchModel.getReview_status())) {
                logger.error("用户删除失败:该用户有未注销的店铺");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSBGYHYWZXDDP, "删除失败:该用户有未注销的店铺", "delUserById");
            }
            //判断该用户是不是分销员
            count = userDistributionModelMapper.counUserDistribution(vo.getStoreId(), user.getUser_id());
            if (count > 0) {
                //用户是否是分销员并且有分销等级
                count = userDistributionModelMapper.countUserDistributionAndHaveLevel(vo.getStoreId(), user.getUser_id());
                if (count > 0){
                    logger.error("用户删除失败:该用户有分销身份");
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSBGYHYFXSF, "删除失败:该用户有分销身份", "delUserById");
                }
                //没有分销等级可以删除
                UserDistributionModel userDistributionModel = new UserDistributionModel();
                userDistributionModel.setStore_id(vo.getStoreId());
                userDistributionModel.setUser_id(user.getUser_id());
                userDistributionModel = userDistributionModelMapper.selectOne1(userDistributionModel);
                if (userDistributionModel != null) {
                    count = userDistributionModelMapper.deleteByPrimaryKey(userDistributionModel);
                    if (count < 1) {
                        throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_FXDJSCSB, "分销等级删除失败");
                    }
                }
            }

            //删除用户
            count = userBaseMapper.deleteByPrimaryKey(id);
            //删除工商信息
            UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
            userBusinessInfo.setUserId(user.getUser_id());
            userBusinessInfoMapper.delete(userBusinessInfo);
            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(), "删除了用户ID："+user.getUser_id()+" 的信息",AdminRecordModel.Type.DEL, vo.getAccessId());
            if (count < 1) {
                logger.error("用户删除失败:用户删除失败");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败", "delUserById");
            }
            //删除用户订单
            OrderModel orderModel = new OrderModel();
            orderModel.setStore_id(vo.getStoreId());
            orderModel.setUser_id(user.getUser_id());
            count = orderModelMapper.delete(orderModel);
            logger.error("删除订单{}个 userid={}", count, user.getUser_id());

            OrderDetailsModel orderDetailsModel = new OrderDetailsModel();
            orderDetailsModel.setStore_id(vo.getStoreId());
            orderDetailsModel.setUser_id(user.getUser_id());
            count = orderDetailsModelMapper.delete(orderDetailsModel);
            logger.error("订单明细删除{}个 userid={}", count, user.getUser_id());
            //删除用户地址
            UserAddress userAddress = new UserAddress();
            userAddress.setStore_id(vo.getStoreId());
            userAddress.setUid(user.getUser_id());
            count = userAddressMapper.delete(userAddress);
            logger.error("用户地址删除{}个 userid={}", count, user.getUser_id());
            //删除用户收藏历史
            UserCollectionModel userCollectionModel = new UserCollectionModel();
            userCollectionModel.setStore_id(vo.getStoreId());
            userCollectionModel.setUser_id(user.getUser_id());
            count = userCollectionModelMapper.delete(userCollectionModel);
            logger.error("用户历史删除{}个 userid={}", count, user.getUser_id());

            //删除用户店铺信息
            MchModel mchDel = new MchModel();
            mchDel.setId(mchDel.getId());
            mchDel.setRecovery(DictionaryConst.ProductRecycle.RECOVERY);
            count = mchModelMapper.updateByPrimaryKeySelective(mchDel);
            logger.error("用户店铺删除{}个 userid={}", count, user.getUser_id());

            return true;
        } catch (LaiKeAPIException l) {
            logger.error(l.getMessage());
            throw l;
        } catch (Exception e) {
            logger.error("删除用户 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delUserById");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(AddUserVo vo) throws LaiKeAPIException {
        try {
            AdminModel adminModel = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
//            if (StringUtils.isEmpty(vo.getUserName())) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_YHMBNWK, "用户名不能为空");
//            }
//            else if (StringUtils.isEmpty(vo.getPhone())) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJHBNWK, "手机号不能为空");
//            }
//            else if (StringUtils.isEmpty(vo.getMima())) {
//                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_MMBNWK, "密码不能为空");
//            }
            if (StringUtils.isEmpty(vo.getMima())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_MMBNWK, "密码不能为空");
            }
            else if (StringUtils.isEmpty(vo.getZhanghao())) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZHBNWK, "账号不能为空");
            }
            User saveUser = new User();
            saveUser.setStore_id(vo.getStoreId());
//            saveUser.setUser_name(vo.getUserName());
//            saveUser.setSource(String.valueOf(vo.getSource()));
            saveUser.setZhanghao(vo.getZhanghao());
            if(StringUtils.isNotEmpty(saveUser.getZhanghao())){
                saveUser.setMobile(vo.getZhanghao());
            }
            saveUser.setGrade(vo.getGrade());
            saveUser.setMima(vo.getMima());
            saveUser.setHeadimgurl(vo.getHeaderUrl());
            //用户类型
            saveUser.setUser_type(GloabConst.UserType.USER_TYPE_BUSINESS);
            //用户角色
            if(StringUtils.isNotEmpty(vo.getRoleId())){
                saveUser.setRole_id(Integer.valueOf(vo.getRoleId()));
            }
            //签约主体为个人
            if(null != vo.getSignatoryType() && vo.getSignatoryType() == 1){
                saveUser.setSignatory_type(vo.getSignatoryType());
                saveUser.setUser_name(vo.getSignatoryName());
                saveUser.setId_card(vo.getIdCard());
                saveUser.setSignatory_name(vo.getSignatoryName());
            }
            //签约主体为企业或个体工商户
            if(null != vo.getSignatoryType() && vo.getSignatoryType() != 1){
                //校验营业执照三要素
                VerifyBusinessData businessData = verifyService.verifyBusinessLicense(vo.getCompanyCreditCode(), vo.getSignatoryName(), vo.getLegalPerson());
                if(businessData == null){
                    logger.error("校验营业执照出错");
                    throw new LaiKeAPIException("校验营业执照三要素错误");
                }
                if(!businessData.isData()){
                    throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERRCODE_BUSINESSNOTSANME,"工商信息不一致");
                }
                saveUser.setSignatory_type(vo.getSignatoryType());
                saveUser.setCompany_name(vo.getSignatoryName());
                saveUser.setCompany_credit_code(vo.getCompanyCreditCode());
                saveUser.setUser_name(vo.getLegalPerson());
                saveUser.setId_card(vo.getLegalPersonIdCard());
                saveUser.setSignatory_name(vo.getSignatoryName());
                //企业资质信息图片
                saveUser.setId_card_face_img(vo.getIdCardFaceImg());
                saveUser.setId_card_back_img(vo.getIdCardBackImg());
                saveUser.setBusiness_license_img(vo.getBusinessLicenseImg());
            }
            saveUser.setProvince(vo.getProvince());
            saveUser.setCity(vo.getCity());
            saveUser.setCounty(vo.getArea());
            saveUser.setDetailed_address(vo.getDetailedAddress());
            saveUser.setDeliveryType(vo.getDeliveryType());
            saveUser.setInvoice(vo.getInvoice());
            saveUser.setSettlementType(vo.getSettlementType());
            saveUser.setIndustry(vo.getIndustry());
            if(StringUtils.isNotEmpty(vo.getSignTime())){
                saveUser.setSign_time(DateUtil.dateFormateToDate(vo.getSignTime(), GloabConst.TimePattern.YMD));
            }
            saveUser.setRemark(vo.getRemark());
            //验证数据
            saveUser = DataCheckTool.checkUserDataFormate(saveUser);
            //账号唯一 手机号唯一
            if (userBaseMapper.validataUserPhoneOrNoIsRegister(vo.getStoreId(), saveUser.getZhanghao()) > 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZHYCZ, "账号" + saveUser.getZhanghao() + "已存在");
            }
            if (userBaseMapper.validataUserPhoneOrNoIsRegister(vo.getStoreId(), saveUser.getMobile()) > 0) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SJHMYCZ, "手机号码" + saveUser.getMobile() + "已存在");
            }
            if (StringUtils.isEmpty(vo.getBirthday()) && StringUtils.isEmpty(vo.getSex())){
                //使用的默认用户配置   性别未知  生日当前时间
                saveUser.setSex(0);
                saveUser.setBirthday(new Date());
                saveUser.setIs_default_value(1);
                saveUser.setIs_default_birthday(1);
            }else {
                saveUser.setIs_default_value(1);
                saveUser.setIs_default_birthday(1);
                saveUser.setSex(vo.getSex());
                saveUser.setBirthday(DateUtil.dateFormateToDate(vo.getBirthday(), GloabConst.TimePattern.YMD));
            }
            //生成userId
            String userId = "user";
            //获取配置信息
            ConfigModel configModel = new ConfigModel();
            configModel.setStore_id(vo.getStoreId());
            configModel = configModelMapper.selectOne(configModel);
            if (configModel != null) {
//                saveUser.setWx_name(configModel.getWx_name());
//                if (StringUtils.isEmpty(saveUser.getHeadimgurl())) {
//                    saveUser.setHeadimgurl(publiceService.getImgPath(configModel.getWx_headimgurl(), vo.getStoreId()));
//                }
                if (StringUtils.isNotEmpty(configModel.getUser_id())) {
                    userId = configModel.getUser_id();
                }
            }
            //获取商城自营店用户
            String zyUserId = customerModelMapper.getStoreUserId(vo.getStoreId());
            User zyUser = new User();
            zyUser.setStore_id(vo.getStoreId());
            zyUser.setUser_id(zyUserId);
            User user = userBaseMapper.selectOne(zyUser);
            if (user == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_QXCJZYD, "请先创建自营店");
            }
            saveUser.setReferee(user.getUser_id());
            //后台新增用户审核状态修改为通过
            saveUser.setExamine_flag(GloabConst.UserExamineFlag.USER_EXAMINE_PASS);
            userBaseMapper.insertSelective(saveUser);

            User userParameter = userBaseMapper.selectByPrimaryKey(saveUser.getId());
            userParameter.setUser_id(userId + (saveUser.getId() + 1));
            int count = userBaseMapper.updateByPrimaryKeySelective(userParameter);
            if (count < 1) {
                logger.error(saveUser.getId() + ": userid生成失败");
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_ZCSBQLXGLY, "注册失败,请联系管理员");
            }
            //签约主体为个人
            if(null != vo.getSignatoryType() && vo.getSignatoryType() == 1){
                UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
                userBusinessInfo.setUserId(userParameter.getUser_id());
                userBusinessInfo.setSignatoryType(vo.getSignatoryType());
                userBusinessInfo.setSignatoryName(vo.getSignatoryName());
                userBusinessInfo.setIdCard(vo.getIdCard());
                userBusinessInfo.setProvince(vo.getProvince());
                userBusinessInfo.setCity(vo.getCity());
                userBusinessInfo.setArea(vo.getArea());
                userBusinessInfo.setAddress(vo.getDetailedAddress());
                userBusinessInfoMapper.insertSelective(userBusinessInfo);
            }
            //签约主体为企业或个体工商户
            if(null != vo.getSignatoryType() && vo.getSignatoryType() != 1){
                UserBusinessInfo userBusinessInfo = new UserBusinessInfo();
                userBusinessInfo.setUserId(userParameter.getUser_id());
                userBusinessInfo.setSignatoryType(vo.getSignatoryType());
                userBusinessInfo.setSignatoryName(vo.getSignatoryName());
                userBusinessInfo.setSignatoryCreditCode(vo.getCompanyCreditCode());
                userBusinessInfo.setProvince(vo.getProvince());
                userBusinessInfo.setCity(vo.getCity());
                userBusinessInfo.setArea(vo.getArea());
                userBusinessInfo.setAddress(vo.getDetailedAddress());
                userBusinessInfo.setRealName(vo.getLegalPerson());
                userBusinessInfo.setIdCard(vo.getLegalPersonIdCard());
                userBusinessInfo.setSignatoryLegalPerson(vo.getLegalPerson());
                userBusinessInfo.setSignatoryLegalPersonIdCard(vo.getLegalPersonIdCard());
                //企业资质信息图片
                userBusinessInfo.setIdCardFaceImg(vo.getIdCardFaceImg());
                userBusinessInfo.setIdCardBackImg(vo.getIdCardBackImg());
                userBusinessInfo.setBusinessLicenseImg(vo.getBusinessLicenseImg());
                userBusinessInfoMapper.insertSelective(userBusinessInfo);
            }
            //获取分销设置
            DistributionConfigModel distributionConfigModel = new DistributionConfigModel();
            distributionConfigModel.setStore_id(vo.getStoreId());
            distributionConfigModel = distributionConfigModelMapper.selectOne(distributionConfigModel);
            //是否是注册绑定永久关系
            if (distributionConfigModel != null && distributionConfigModel.getRelationship().equals(DistributionConfigModel.RelationshipType.PLUGIN_OPEN)){
                logger.info("分销商注册绑定永久关系 创建分销商={}和上级绑定永久关系上级={}", userParameter.getUser_id(), user.getUser_id());
                publiceDistributionService.createLevel(vo.getStoreId(), userParameter.getUser_id(), 0, user.getUser_id());
            }
            //添加操作日志
            publiceService.addAdminRecord(vo.getStoreId(), "添加了用户ID："+userId + (saveUser.getId() + 1),AdminRecordModel.Type.ADD, vo.getAccessId());

        } catch (LaiKeAPIException l) {
            logger.error(l.getMessage());
            throw l;
        } catch (Exception e) {
            logger.error("后台添加会员 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delUserById");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void uploadAddUser(MainVo vo, List<MultipartFile> image) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            ExcelAnalysisVo excelAnalysisVo = new ExcelAnalysisVo();
            excelAnalysisVo.setFile(image);
            List<String> titleNames = new ArrayList<>();
            titleNames.add("用户账号");
            titleNames.add("用户密码");
            titleNames.add("手机号码");
            titleNames.add("账号来源");
            excelAnalysisVo.setTitleName(titleNames);
            List<String> valueNames = new ArrayList<>();
            valueNames.add("account");
            valueNames.add("password");
            valueNames.add("phone");
            valueNames.add("source");
            excelAnalysisVo.setValueKey(valueNames);
            Map<String, Object> resultMap = EasyPoiExcelUtil.analysisExcel(excelAnalysisVo);
            List<Map<String, Object>> excelDataList = DataUtils.cast(resultMap.get("list"));
            if (excelDataList != null) {
                List<AddUserVo> addUserVoList = new ArrayList<>();
                String fileName = "";
                StringBuilder errorText = new StringBuilder("");
                label:
                for (Map<String, Object> map : excelDataList) {
                    int x = MapUtils.getIntValue(map, "x");
                    fileName = MapUtils.getString(map, "fileName", "");
                    errorText.append(MapUtils.getString(map, "errorText"));
                    if (map.containsKey("account")) {
                        //用户头像
                        String userHeadUrl = "";
                        //用户昵称
                        String userName = "";
                        //用户账号
                        String account = MapUtils.getString(map, "account");
                        //用户密码
                        String password = MapUtils.getString(map, "password");
                        //用户手机号
                        String phone = MapUtils.getString(map, "phone");
                        //账号来源
                        String source = MapUtils.getString(map, "source");
                        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(password) || StringUtils.isEmpty(phone)) {
                            errorText.append(String.format("第%s行 %s", x, "请完善正确的用户账号、用户密码及用户手机号和账号来源")).append(SplitUtils.DH);
                            break;
                        }
                        //系统默认头像/昵称
                        ConfigModel configModel = new ConfigModel();
                        configModel.setStore_id(vo.getStoreId());
                        configModel = configModelMapper.selectOne(configModel);
                        if (configModel != null) {
                            if (configModel.getWx_headimgurl() == null || configModel.getWx_name() == null){
                                errorText.append("请先完成用户设置").append(SplitUtils.DH);
                                break;
                            }
                            userHeadUrl = publiceService.getImgPath(configModel.getWx_headimgurl(), vo.getStoreId());
                            userName = configModel.getWx_name();
                        }

                        AddUserVo addUserVo = new AddUserVo();
                        addUserVo.setStoreId(vo.getStoreId());
                        addUserVo.setHeaderUrl(userHeadUrl);
                        addUserVo.setUserName(userName);
                        addUserVo.setZhanghao(account);
                        addUserVo.setMima(password);
                        addUserVo.setPhone(phone);
                        switch (source) {
                            case "pc端":
                                addUserVo.setSource(Integer.valueOf(DictionaryConst.StoreSource.LKT_LY_006));
                                break;
                            case "小程序":
                                addUserVo.setSource(Integer.valueOf(DictionaryConst.StoreSource.LKT_LY_001));
                                break;
                            case "APP端":
                                addUserVo.setSource(Integer.valueOf(DictionaryConst.StoreSource.LKT_LY_011));
                                break;
                            case "H5移动端":
                                addUserVo.setSource(Integer.valueOf(DictionaryConst.StoreSource.LKT_LY_002));
                                break;
                            default:
                                errorText.append(String.format("第%s行 %s", x, "请完善正确的账号来源:pc端,小程序,APP端,H5移动端")).append(SplitUtils.DH);
                                break label;
                        }
                        addUserVo.setAccessId(vo.getAccessId());
                        addUserVoList.add(addUserVo);
                    }
                }
                try {
                    extracted(addUserVoList, errorText);
                }catch (LaiKeAPIException ignored){

                }

                //记录
                FileDeliveryModel fileDeliveryModel = new FileDeliveryModel();
                fileDeliveryModel.setId(BuilderIDTool.getSnowflakeId() + "");
                fileDeliveryModel.setName(fileName);
                fileDeliveryModel.setAdd_date(new Date());
                int status = 1;
                if (StringUtils.isNotEmpty(errorText)) {
                    status = 0;
                    fileDeliveryModel.setText(errorText.toString());
                }
                fileDeliveryModel.setStatus(status);
                fileDeliveryModel.setType(2);
                fileDeliveryModel.setMch_id(user.getShop_id());
                fileDeliveryModelMapper.insertSelective(fileDeliveryModel);

                publiceService.addAdminRecord(vo.getStoreId(), "执行了批量导入用户操作",AdminRecordModel.Type.ADD, vo.getAccessId());
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("批量添加用户 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadAddGoods");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<AddUserVo> addUserVoList, StringBuilder errorText) {
        //设置回滚点
        int errorLineIndex = 1;
        try {
            if (StringUtils.isEmpty(errorText.toString())) {
                for (AddUserVo addUserVo : addUserVoList) {
                    logger.debug("================== 正在添加用户:" + addUserVo.getPhone() + "========================");
                    logger.debug("手机号:{} 账号:{}", addUserVo.getPhone(), addUserVo.getZhanghao());
                    try {
                        this.saveUser(addUserVo);
                    } finally {
                        logger.debug("================== 添加用户结束 ========================");
                        errorLineIndex++;
                    }
                }
            }
        } catch (LaiKeAPIException l) {
            logger.error("批量上传用户 异常", l);
            //回滚
            errorText.append(String.format("第%s行 %s", errorLineIndex, l.getMessage())).append(SplitUtils.DH);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadAddGoods");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delUploadRecord(MainVo vo, String id) throws LaiKeAPIException {
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            FileDeliveryModel fileDeliveryModel = fileDeliveryModelMapper.selectByPrimaryKey(id);
            if (fileDeliveryModel == null) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_JLBCZ, "记录不存在");
            }
            int row = fileDeliveryModelMapper.deleteByPrimaryKey(id);
            if (row < 1) {
                throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_SCSB, "删除失败");
            }
            publiceService.addAdminRecord(vo.getStoreId(), "删除了文件id："+id+" 的批量用户导入记录的信息",AdminRecordModel.Type.DEL,vo.getAccessId());
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("删除导入记录 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "delUploadRecord");
        }
    }

    @Override
    public Map<String, Object> uploadRecordList(MainVo vo, String key, Integer status, String startDate, String endDate) throws LaiKeAPIException {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            AdminModel user = RedisDataTool.getRedisAdminUserCache(vo.getAccessId(), redisUtil);
            Map<String, Object> paramMap = new HashMap<>(16);
            paramMap.put("mchId", user.getShop_id());
            paramMap.put("name", key);
            paramMap.put("type", 2);
            paramMap.put("status", status);
            paramMap.put("startDate", startDate);
            paramMap.put("endDate", endDate);
            paramMap.put("add_date_sort", DataUtils.Sort.DESC.toString());
            paramMap.put("pageStart", vo.getPageNo());
            paramMap.put("pageEnd", vo.getPageSize());

            int total = fileDeliveryModelMapper.countDynamic(paramMap);
            List<Map<String, Object>> resultList = new ArrayList<>();
            if (total > 0) {
                resultList = fileDeliveryModelMapper.selectDynamic(paramMap);
            }

            resultMap.put("total", total);
            resultMap.put("list", resultList);
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            logger.error("批量上传记录列表 异常", e);
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "uploadRecordList");
        }
        return resultMap;
    }


    @Autowired
    private UserBaseMapper userBaseMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private UserGradeModelMapper userGradeModelMapper;

    @Autowired
    private MchModelMapper mchModelMapper;

    @Autowired
    private PublicUserService publicUserService;

    @Autowired
    private UserDistributionModelMapper userDistributionModelMapper;

    @Autowired
    private OrderDetailsModelMapper orderDetailsModelMapper;

    @Autowired
    private UserAddressMapper userAddressMapper;

    @Autowired
    private UserCollectionModelMapper userCollectionModelMapper;

    @Autowired
    private UserRuleModelMapper userRuleModelMapper;

    @Autowired
    private DistributionConfigModelMapper distributionConfigModelMapper;

    @Autowired
    private PubliceDistributionService publiceDistributionService;
}

